<template>
  <div class="page-header">
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>角色管理</el-breadcrumb-item>
    </el-breadcrumb>
  </div>
  <el-card class="box-card">
    <template #header>
      <div class="card-header">
        <el-button plain size="small" type="primary" @click="handleAdd">新增</el-button>
      </div>
    </template>

    <el-table :data="roles" border size="small" style="width: 100%">
      <el-table-column prop="id" label="角色ID"></el-table-column>
      <el-table-column prop="name" label="角色名"></el-table-column>
      <el-table-column label="权限">
        <template #default="scope">
          <el-tag
            v-for="menu in scope.row.menus"
            :key="menu.id"
            type="danger"
            size="medium"
          >{{ menu.name }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="created_at" label="创建时间"></el-table-column>
      <el-table-column fixed="right" label="操作">
        <template #default="scope">
          <el-button @click="handleEdit(scope.row)" type="text" size="small">编辑</el-button>
          <el-popconfirm title="确认删除？" @confirm="handleDel(scope.row.id, scope.row.$index)">
            <template #reference>
              <el-button type="text" size="small">删除</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
  </el-card>
  <role-form :role="role" v-model:dialogVisible="dialogVisible" @reload="loadRoles"></role-form>
</template>

<script setup>
import roleForm from './Form.vue'
import { ElMessage } from "element-plus";
import { toRefs, reactive, onMounted } from "vue"
import { getRoles, delRole } from "../../api/role"

const state = reactive({
  dialogVisible: false,
  roles: [],
  role: {
    id: null,
    name: null,
    menuIds: [],
  },
})

const handleAdd = () => {
  state.role = {}
  state.dialogVisible = true
}

const handleEdit = (user) => {
  state.role.id = user.id
  state.role.name = user.name
  state.role.menuIds = user.menus.map(item => Number(item.id))

  state.dialogVisible = true
}

const handleDel = (id, index) => {
  delRole(id).then(result => {
    if (result.status === 'success') {
      state.roles.splice(index, 1)
    } else {
      ElMessage.error("删除失败")
    }
  })
}

const loadRoles = () => {
  getRoles().then(result => {
    state.roles = result.roles
  })
}

loadRoles()

const { dialogVisible, roles, role } = toRefs(state)
</script>

<style scoped>
.el-tag {
  margin-right: 10px;
  margin-bottom: 10px;
}
.box-card {
  margin: 20px;
  max-height: calc(100% - 100px);
  width: calc(100% - 40px);
  box-sizing: border-box;
  overflow: auto;
}
</style>